import { useEffect, useMemo, useState } from 'react'
import { InputNumber, InputNumberProps } from 'antd'

export interface MaxMinDayValue {
  minVal?: number
  maxVal?: number
}

type MaxMinDayProps = Omit<InputNumberProps, 'value' | 'onChange'> & {
  value?: MaxMinDayValue
  onChange?: (value: MaxMinDayValue) => void
}

export const MaxMinDay = ({ value = {}, onChange, ...rest }: MaxMinDayProps) => {
  const [minValState, setMinValState] = useState(value.minVal)
  const [maxValState, setMaxValState] = useState(value.maxVal)

  // 计算各自的最大最小值限制
  const { minInputMax, maxInputMin } = useMemo(() => {
    return {
      minInputMax: maxValState !== undefined ? maxValState : undefined,
      maxInputMin: minValState !== undefined ? minValState : undefined,
    }
  }, [minValState, maxValState])

  const handleMinChange = (newMinVal: string | number | null) => {
    const numVal = typeof newMinVal === 'string' ? parseFloat(newMinVal) : newMinVal
    const safeMinVal = numVal ?? undefined
    let adjustedMaxVal = maxValState

    // 如果新的最小值大于当前最大值，自动调整最大值
    if (safeMinVal !== undefined && maxValState !== undefined && safeMinVal > maxValState) {
      adjustedMaxVal = safeMinVal
    }

    onChange?.({
      minVal: safeMinVal,
      maxVal: adjustedMaxVal,
    })
  }

  const handleMaxChange = (newMaxVal: string | number | null) => {
    const numVal = typeof newMaxVal === 'string' ? parseFloat(newMaxVal) : newMaxVal
    const safeMaxVal = numVal ?? undefined
    let adjustedMinVal = minValState

    // 如果新的最大值小于当前最小值，自动调整最小值
    if (safeMaxVal !== undefined && minValState !== undefined && safeMaxVal < minValState) {
      adjustedMinVal = safeMaxVal
    }

    onChange?.({
      minVal: adjustedMinVal,
      maxVal: safeMaxVal,
    })
  }

  useEffect(() => {
    setMinValState(value.minVal)
    setMaxValState(value.maxVal)
  }, [value])

  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
      <InputNumber
        {...rest}
        value={minValState}
        onChange={handleMinChange}
        max={minInputMax}
        placeholder="最小值"
        style={{ flex: 1 }}
        controls={false}
      />
      <span style={{ color: '#999', fontSize: '14px' }}>~</span>
      <InputNumber
        {...rest}
        value={maxValState}
        onChange={handleMaxChange}
        min={maxInputMin}
        placeholder="最大值"
        style={{ flex: 1 }}
        controls={false}
      />
      <span>天</span>
    </div>
  )
}
